package com.rimuru.datastructure.linkedlist;

import java.util.Iterator;

/**
 * 环型链表
 */
public class CircleLinkedListSentinel implements Iterable<Integer> {

    static class Node {
        Node prev; // 上一个节点指针
        int value; // 值
        Node next; // 下一个节点指针

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    private Node sentinel = new Node(null, -1, null);

    public CircleLinkedListSentinel() {
        sentinel.prev = sentinel;
        sentinel.next = sentinel;
    }

    private Node findNode(int value) {
        Node p = sentinel.next;
        while (p != sentinel) {
            if (p.value == value) {
                return p;
            }
            p = p.next;
        }
        return null;
    }

    public void addFirst(int value) {
        Node node = new Node(sentinel, value, sentinel.next);
        sentinel.next.prev = node;
        sentinel.next = node;
    }

    public void removeFirst() {
        if(sentinel == sentinel.next) {
            throw new IllegalArgumentException("非法");
        }
        Node next = sentinel.next.next;
        sentinel.next = next;
        next.prev = sentinel;

    }

    public void addLast(int value) {
        Node node = new Node(sentinel.prev, value, sentinel);
        sentinel.prev.next = node;
        sentinel.prev = node;
    }

    public void removeLast() {
        Node last = sentinel.prev;
        if(last == sentinel) {
            throw illegalIndex(0);
        }
        sentinel.prev = last.prev;
        last.prev.next = sentinel;

    }


    // 根据目标值删除
    public void removeByValue(int value) {
        Node removed = findNode(value);
        if (removed == null) {
            return;
        }
        removed.prev.next = removed.next;
        removed.next.prev = removed.prev;
    }

    private IllegalArgumentException illegalIndex(int index) {
        return new IllegalArgumentException(
                String.format("index [%d] 不合法%n", index));
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {

            Node p = sentinel.next;

            @Override
            public boolean hasNext() {
                return p != sentinel;
            }

            @Override
            public Integer next() {
                int value = p.value;
                p = p.next;
                return value;
            }
        };
    }
}
